import _ from 'lodash'
import plotxyOption from './plotxy'
import radarOption from './radar'
import pieOption from './pie'
import { getTheme } from './theme'

/**
 * plotxy:二维图(柱状,折线,散点等)
 * radar: 雷达图
 * pie: 饼图
 */

const typeMapping = {
  plotxy: ['line', 'bar', 'scatter', 'k', 'candlestick', 'bubble'],
  radar: ['radar'],
  pie: ['pie']
}

function getType(types) {
  let t = []
  types.forEach((item) => {
    Object.values(typeMapping).forEach((child, childIndex) => {
      if (child.includes(item)) {
        t = t.concat(Object.keys(typeMapping)[childIndex])
      }
    })
  })
  t = _.uniq(t)
  if (_.size(t) === 1) {
    return t[0]
  }
  return null
}

function switchRender(types, option) {
  let type = ''
  let render = null
  if (option.yAxis || option.xAxis) {
    type = 'plotxy'
    render = plotxyOption
  }
  const t = getType(types)
  switch (t) {
    case 'plotxy':
      type = 'plotxy'
      render = plotxyOption
      break
    case 'radar':
      type = 'radar'
      render = radarOption
      break
    case 'pie':
      type = 'pie'
      render = pieOption
      break
    default:
      break
  }
  return {
    type,
    render
  }
}

function renderOption(type = 'plotxy', option = {}, theme) {
  const _theme = getTheme(theme)
  let result = option
  const params = {
    option,
    theme: _theme,
    chartTheme: _theme[type]
  }
  if (!type || type === '' || type === 'plotxy') {
    result = plotxyOption(params)
  } else if (type === 'radar') {
    result = radarOption(params)
  } else if (type === 'pie') {
    result = pieOption(params)
  }
  return result
}

function renderEchartsOption(option = {}, theme) {
  const _theme = getTheme(theme)
  const { series } = option
  let types = []
  if (series) {
    if (_.isObjectLike(series)) {
      if (_.isArray(series)) {
        types = series.map((item) => item.type)
        types = _.uniq(types)
      } else {
        types = [series.type]
      }
    }
  }
  const { type, render } = switchRender(types, option)
  if (render) {
    return render({
      option,
      theme: _theme,
      chartTheme: _theme[type]
    })
  }
  return option
}
export { renderOption, renderEchartsOption }
